600. Client Side Data Fetching
- You might not always need to pre-render the data
- ex: A dashboard that is
- behind a login screen
- highly user-specific, thus SEO not relevant
- for this kind of website, no need to pre-render the data, we can rely on the client side data fetching
- ex: A dashboard that is
Client Side Data Fetching with Fetch
import {useEffect, useState} from "react";
function Carts() {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState(null);
useEffect(() => {
async function loadCarts() {
const response = await fetch("https://dummyjson.com/carts");
const data = await response.json();
setData(data.carts);
setIsLoading(false);
}
loadCarts();
}, [])
if (isLoading) {
return <h3>Cart loading...</h3>
}
return (
<>
<h3>Showing {data.length} carts</h3>
{
data.map(cart => {
return <div key={cart.id}>
<h3>Total price == {cart.total}</h3>
<p>Total Quantity == {cart.totalQuantity}</p>
</div>
})
}
</>
)
}
export default Carts;
Client Side Data Fetching with SWR
- SWR DOC
- SWR is derived from
stale-while-revalidate
.- SWR is a strategy to first return the data from cache(stale), then send the fetch request(re-validate), and finally come with the up-to-date data.
- can handle
- caching
- re-validation
- pagination
- suspense
- ..
import useSWR from 'swr'
// const fetcher = fetch("https://dummyjson.com/carts").then(res => res.json());
const fetcher = (args) => fetch(args).then(res => res.json())
function Carts() {
const {data, error} = useSWR("https://dummyjson.com/carts", fetcher);
if (error){
return <h3>error occured</h3>
}
if (!data) {
return <h3>Cart loading...</h3>
}
return (
<>
<h3>Showing {data.carts.length} carts</h3>
{
data.carts.map(cart => {
return <div key={cart.id}>
<h3>Total price == {cart.total}</h3>
<p>Total Quantity == {cart.totalQuantity}</p>
</div>
})
}
</>
)
}
export default Carts;
Client Side Fetching with Plus Pre Rendering
import {useState} from "react";
import {useRouter} from "next/router";
function Products({productList}) {
const [products, setProducts] = useState(productList);
const router = useRouter();
const filterProducts = async () => {
const response = await fetch(`https://dummyjson.com/products/category/laptops`);
const data = await response.json();
setProducts(data.products);
router.push("/carts/server-client?category=laptops", undefined, {shallow: true})
}
return (
<div>
<button onClick={filterProducts}>Filter only laptops</button>
{
products.map(product => {
return <div key={product.id}>
<h2>{product.title}</h2>
<p>{product.description}</p>
</div>
})
}
</div>
)
}
export default Products;
export async function getServerSideProps(context) {
const {query} = context
const {category} = query;
const queryString = category || 'smartphones';
const response = await fetch(`https://dummyjson.com/products/category/${queryString}`);
const data = await response.json();
return {
props: {
productList: data.products
}
}
}